// pages/indexs/shijian/shijian.js
var util = require("../../../utils/util.js")
const api = require('../../../api/index.js')
let baseURL = 'https://www.didigolf.top/';
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tokenState: false,
    dayStyle: [{
      month: "current",
      day: new Date().getDate() + 1,
      color: '#000000',
      background: '#FFE400'
    }],
    time: false,
    morning: [],
    checked: 0,
    appointTime: "未选择",
    num: 1,
    hide: true,
    prevShow: true,
    nextShow: false,
    a: true,
    year: 0,
    month: 0,
    dates: ['日', '一', '二', '三', '四', '五', '六'],
    dateArr: [],
    isToday: 0,
    isTodayWeek: false,
    todayIndex: 0
  },

  //给点击的日期设置一个背景颜色
  dayClick: function(e) {
    var event = e.currentTarget.dataset.date.split("-")
    let clickDay = parseInt(event[2]);
    let clickMonth = event[1];
    let clickYear = event[0]
    let changeDay = `dayStyle[0].day`;
    let changeBg = `dayStyle[0].background`;
    console.log([changeDay])
    console.log(changeBg)
    var morning = this.data.morning
    var year = new Date().getYear()
    var day = new Date().getDate()
    var month = new Date().getMonth() + 1
    if (year < clickYear) {
      morning.forEach(function(element) {
        element.disable = false
      })
    } else if (clickMonth > month) {
      morning.forEach(function(element) {
        element.disable = false
      })
    } else if (clickDay > day) {
      morning.forEach(function(element) {
        element.disable = false
      })
    } else if (clickDay < day) {
      morning.forEach(function(element) {
        element.disable = true
        element.checked = false
      })
    } else {
      var hour = new Date().getHours();
      var minute = new Date().getMinutes();
      var morning = this.data.morning
      // var appointTime = ""
      for (var i = 0; i < morning.length; i++) {
        morning[i].date = morning[i].time.split(":")
        if (morning[i].date[0] < hour) {
          morning[i].disable = true
        } else if (hour == morning[i].date[0] && minute >= morning[i].date[1]) {
          morning[i].disable = true
        } else {
          morning[i].disable = false
        }
      }
    }

    var date = e.currentTarget.dataset.date;
    var p_price = ""
    var a = false
    var is_vip_day = ""
    var result = this.data.date
    result.forEach(function(element) {
      if (element.date == date) {
        a = true
        p_price = element.price
        is_vip_day = element.is_vip_day
      }
    })

    if (!a) {
      wx.showModal({
        title: '提示',
        content: '当前时间不能选择',
        showCancel: false,
        success(res) {}
      })
      this.setData({
        a: a
      })
    } else {
      this.setData({
        p_price: p_price,
        price: p_price,
        isToday: date,
        morning: morning,
        a: a,
        newDate: date,
        is_vip_day: is_vip_day
      })
    }
  },

  formatNumber: function(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },

  //控制时间显示隐藏，改变time值，如果是true显示，false隐藏
  time: function() {
    console.log(this.data.a)
    if (!this.data.a) {
      wx.showModal({
        title: '提示',
        content: '当前时间不能选择',
        showCancel: false,
        success(res) {}
      })
    } else {
      this.setData({
        display: "block"
      })
    }
  },
  hideview: function() {
    this.setData({
      display: "none"
    })
  },
  selectMorning: function(e) {
    var item = e.currentTarget.id
    var morning = this.data.morning
    morning.forEach(function(ele) {
      if (ele.time == item) {
        ele.checked = true
      } else {
        ele.checked = false
      }
    })
    this.setData({
      morning: morning,
      appointTime: item,
      display: "none"
    })
  },
  selectAfternoon: function(e) {
    var item = e.currentTarget.id
    this.setData({
      checked: item,
      appointTime: item,
      display: "none"
    })
  },

  jian: function() {
    var num = this.data.num
    var hide = this.data.hide
    if (num > 2) {
      num = num - 1
      hide = false
    } else {
      num = 1
      hide = true
    }
    this.setData({
      num: num,
      hide: hide
    })
  },

  jia: function() {
    var num = this.data.num
    num = num + 1
    this.setData({
      num: num,
      hide: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    console.log(price)
    var that = this
    var data = {}
    data.e_id = options.e_id
    var is_vip_day = 0
    var price = ""
    var date = util.formatDateTo(new Date())
    api.timeBooking(data, (res) => {
      console.log(res)
      var dateResult = res.data.result.content
      var dateItem = ""
      var is_vip_day = 0
      for (var m = 0; m < dateResult.length; m++) {
        dateItem = dateResult[0].date
        is_vip_day = dateResult[0].is_vip_day
      }
      console.log(dateItem, "这是接口给出的第一个日期")
      that.setData({
        date: res.data.result.content,
        is_vip_day: is_vip_day,
        isDate: dateItem,
        isToday: dateItem
      })

      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      that.dateInit();
      that.setData({
        year: year,
        month: month
      })

      var hour = new Date().getHours();
      var minute = new Date().getMinutes();
      var morning = res.data.result.time

      var appointTime = ""
      for (var i = 0; i < morning.length; i++) {
        morning[i].disable = false
        morning[i].date = morning[i].time.split(":")
      }
      that.setData({
        morning: morning,
        price: options.price,
        p_price: options.p_price,
        e_id: options.e_id,
        newDate: date
      })
    })


    api.particulars(data, (res) => {
      console.log(res)
      that.setData({
        content: res.data.result
      })
    })

    app.Logins();
    let token = wx.getStorageSync("token").token
    console.log(token, '看看有没有token')
    if (token == undefined || token == null || token == null) {
      this.setData({
        Loing: true
      })
    }
    if (!token) {
      console.log('iftoken')
      this.setData({
        Loing: true
      })
    }


  },
  getPhoneNumber: function(e) {
    let sessionKeyS = wx.getStorageSync('session_key').session_key;
    console.log(sessionKeyS);
    if (sessionKeyS == '' || sessionKeyS == undefined) {
      app.Logins();
    }
    let invite_id = wx.getStorageSync('invite_id');
    let data = {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      sessionKey: sessionKeyS,
      invite_id: invite_id
    }
    console.log(data);
    api.getPhoneNumber(data, (res) => {
      if (res.data.code == 50003) {
        this.setData({
          tokenState: true
        })
        wx.showToast({
          title: '亲，登录需要授权哦~',
          icon: 'none',
          duration: 2000
        })
      } else {
        this.setData({
          userData: res.data.result,
          tokenState: false
        })

        app.globalData.Refresh = true;
        wx.setStorageSync('token', {
          "token": res.data.result.token,
          "user_mobile": res.data.result.user_mobile
        });
        wx.navigateTo({
          url: '../yuyue/yuyue?e_id=' + this.data.e_id + '&num=' + this.data.num + '&time=' + this.data.isToday + ' ' + this.data.appointTime + '&is_vip_day=' + this.data.is_vip_day
        })
        console.log(wx.getStorageSync('token'))
      }
    })
  },





  // 下一步
  yuyue: function() {
    var that = this
    var content = this.data.content
    if (this.data.appointTime == "未选择") {
      wx.showModal({
        title: '提示',
        content: '请选择预约时间',
        showCancel: false,
        success(res) {}
      })
    } else if (0 === getApp().messages()) {
      console.log("token")
      that.setData({
        tokenState: true
      })
    } else {
      wx.navigateTo({
        url: '../yuyue/yuyue?e_id=' + this.data.e_id + '&num=' + this.data.num + '&time=' + this.data.isToday + ' ' + this.data.appointTime + '&is_vip_day=' + this.data.is_vip_day
      })
    }

  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  getNowDate: function() {
    var date = new Date();
    var sign1 = "/";
    var sign2 = ":";
    var year = date.getFullYear() // 年
    var month = date.getMonth() + 1; // 月
    var day = date.getDate(); // 日
    var hour = date.getHours(); // 时
    var minutes = date.getMinutes(); // 分
    var seconds = date.getSeconds() //秒
    // 给一位数数据前面加 “0”
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
      day = "0" + day;
    }
    if (hour >= 0 && hour <= 9) {
      hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
      minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
      seconds = "0" + seconds;
    }
    var currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds;
    return currentdate;
  },

  formatTimeTwo(number, format) {

    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    var returnArr = [];

    var date = new Date(number * 1000);
    returnArr.push(date.getFullYear());
    returnArr.push(formatNumber(date.getMonth() + 1));
    returnArr.push(formatNumber(date.getDate()));

    returnArr.push(formatNumber(date.getHours()));
    returnArr.push(formatNumber(date.getMinutes()));
    returnArr.push(formatNumber(date.getSeconds()));

    for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
  },

  dateInit: function(setYear, setMonth) {
    var that = this
    //全部时间的月份都是按0~11基准，显示月份才+1
    // var time = that.getNowDate();
    // var times = that.getNowDate();
    let dateArr = []; //需要遍历的日历数组数据
    let arrLen = 0; //dateArr的数组长度
    let now = setYear ? new Date(setYear, setMonth) : new Date();
    console.log(now)
    let year = setYear || now.getFullYear();
    let nextYear = 0;
    let month = setMonth || now.getMonth(); //没有+1方便后面计算当月总天数
    let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
    let startWeek = new Date(year + '/' + (month + 1) + '/' + 1).getDay(); //目标月1号对应的星期
    let dayNums = new Date(year, nextMonth, 0).getDate(); //获取目标月有多少天
    let obj = {};
    let num = 0;

    if (month + 1 > 11) {
      nextYear = year + 1;
      dayNums = new Date(nextYear, nextMonth, 0).getDate();
    }
    arrLen = startWeek + dayNums;
    for (let i = 0; i < arrLen; i++) {
      if (i >= startWeek) {
        num = i - startWeek + 1;
        obj = {
          // isToday: '' + year + "-" + (month + 1) + "-" + num,
          isToday: [year, (month + 1), num].map(that.formatNumber).join('-'),
          dateNum: num,
          weight: 5
        }
      } else {
        obj = {
          isToday: "",
          dateNum: "",
          weight: ""
        };
      }
      dateArr[i] = obj;
    }
    // console.log(dateArr)
    that.setData({
      dateArr: dateArr
    })

    let nowDate = new Date();
    let nowYear = nowDate.getFullYear();
    let nowMonth = nowDate.getMonth() + 1;
    let nowWeek = nowDate.getDay();
    let getYear = setYear || nowYear;
    let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;

    if (nowYear == getYear && nowMonth == getMonth) {
      that.setData({
        isTodayWeek: true,
        todayIndex: nowWeek
      })
    } else {
      that.setData({
        isTodayWeek: false,
        todayIndex: -1
      })
    }
  },
  lastMonth: function() {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
    let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
    this.setData({
      year: year,
      month: (month + 1),
      prevShow: true,
      nextShow: false
    })
    this.dateInit(year, month);
  },
  nextMonth: function() {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
    let month = this.data.month > 11 ? 0 : this.data.month;
    this.setData({
      year: year,
      month: (month + 1),
      prevShow: false,
      nextShow: true
    })
    this.dateInit(year, month);
  }

})